{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from scipy import signal\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "\n",
    "t = np.linspace(0, 1.0, 2001)\n",
    "xlow = np.sin(2 * np.pi * 5 * t)\n",
    "xhigh = np.sin(2 * np.pi * 250 * t)\n",
    "x = xlow + xhigh\n",
    "\n",
    "\n",
    "b, a = signal.butter(8, 0.125)\n",
    "y = signal.filtfilt(b, a, x, padlen=150)\n",
    "np.abs(y - xlow).max()\n",
    "\n",
    "\n",
    "b, a = signal.ellip(4, 0.01, 120, 0.125)  # Filter to be applied.\n",
    "\n",
    "\n",
    "rng = np.random.default_rng()\n",
    "n = 60\n",
    "sig = rng.standard_normal(n)**3 + 3*rng.standard_normal(n).cumsum()\n",
    "\n",
    "\n",
    "fgust = signal.filtfilt(b, a, sig, method=\"gust\")\n",
    "fpad = signal.filtfilt(b, a, sig, padlen=50)\n",
    "plt.plot(sig, 'k-', label='input')\n",
    "plt.plot(fgust, 'b-', linewidth=4, label='gust')\n",
    "plt.plot(fpad, 'c-', linewidth=1.5, label='pad')\n",
    "plt.legend(loc='best')\n",
    "plt.show()\n",
    "\n",
    "\n",
    "z, p, k = signal.tf2zpk(b, a)\n",
    "eps = 1e-9\n",
    "r = np.max(np.abs(p))\n",
    "approx_impulse_len = int(np.ceil(np.log(eps) / np.log(r)))\n",
    "# approx_impulse_len\n",
    "\n",
    "\n",
    "x = rng.standard_normal(4000)\n",
    "y1 = signal.filtfilt(b, a, x, method='gust')\n",
    "y2 = signal.filtfilt(b, a, x, method='gust', irlen=approx_impulse_len)\n",
    "print(np.max(np.abs(y1 - y2)))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
